package com.vehiclemanagement.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * Jackson配置类
 * 用于处理日期时间的序列化和反序列化
 */
@Configuration
public class JacksonConfig {

    /**
     * 默认日期时间格式
     */
    public static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    
    /**
     * 日期格式化
     */
    public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN);
    
    /**
     * 简单日期格式（不含时间）
     */
    public static final String SIMPLE_DATE_PATTERN = "yyyy-MM-dd";
    
    /**
     * 简单日期格式化
     */
    public static final DateTimeFormatter SIMPLE_DATE_FORMATTER = DateTimeFormatter.ofPattern(SIMPLE_DATE_PATTERN);

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 配置忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // 配置LocalDateTime的序列化器和反序列化器
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DATETIME_FORMATTER));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DATETIME_FORMATTER) {
            @Override
            public LocalDateTime deserialize(com.fasterxml.jackson.core.JsonParser parser, com.fasterxml.jackson.databind.DeserializationContext context) 
                    throws java.io.IOException {
                String dateStr = parser.getText().trim();
                try {
                    // 尝试使用默认格式解析
                    return LocalDateTime.parse(dateStr, DATETIME_FORMATTER);
                } catch (DateTimeParseException e) {
                    try {
                        // 如果默认格式失败，尝试使用简单日期格式，并设置时间为00:00:00
                        return LocalDateTime.parse(dateStr + " 00:00:00", DATETIME_FORMATTER);
                    } catch (DateTimeParseException ex) {
                        throw new IllegalArgumentException("无法解析日期时间: " + dateStr + 
                                "，支持的格式为: " + DEFAULT_DATETIME_PATTERN + " 或 " + SIMPLE_DATE_PATTERN);
                    }
                }
            }
        });
        
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }
} 